package demo10;

import java.util.Arrays;

/**
 * sort (b merge a)
 */
public class SortForUpdatePosDemo2 {
    public BaseLineSort createBaseLineSort() {
        return new BaseLineSort();
    }

    public class BaseLineSort {
        MergeSortDemo2.MergeSort mergeSort = null;

        public BaseLineSort() {
            MergeSortDemo2 mergeSortDemo2 = new MergeSortDemo2();
            mergeSort = mergeSortDemo2.createMergeSort();

        }

        /**
         * int a = 123
         * int b = 312
         * group by number  in the 个位
         * digital exp   = 3
         * group=>[ b ]
         * <p>
         * String str1 = "aba" ;
         * String str2 = "edf" ;
         * String str3 = "aab" ;
         * String str4 = "fde" ;
         * => ["aba","aab","edf","fde"]
         */
        public void group(int[] arr) {
            // k: count(elements), n:位数  o(kn)
            // String[] contains the aba , group it
            // how to group , foreach
            // get the lowest pos ,  and others numbers
            group(arr, 1, false);


        }

        public void group(int[] arr, int multiple, boolean overFlag) {
            if (overFlag) {
                return;
            }
            overFlag=true;
            int[] tempHighArr = new int[arr.length];
            int[] tempLowArr = new int[arr.length];

            int currentHigh = 0, currentLow = 0;
            for (int i = 0; i < arr.length; i++) {
                if ((arr[i] / multiple) == 0) {
                    tempLowArr[currentLow++] = arr[i];
                } else {
                    tempHighArr[currentHigh++] = arr[i];
                    overFlag = false;
                }
            }
            sort(tempLowArr, currentLow);
            tempHighArr = clip(tempHighArr, currentHigh);
            group(tempHighArr, multiple * 10, overFlag);

        }

        private void sort(int[] tempLowArr, int size) {

            tempLowArr = clip(tempLowArr, size);

            // use mergeSort , plus the Time O(nlogn)
            mergeSort.mergeSort(tempLowArr);

            Arrays.stream(tempLowArr).forEach(s -> {
                System.out.print(s + ",");
            });

        }

//        private void sort(int[] tempLowArr, int size) {
//            tempLowArr = clip(tempLowArr, size);
//
//            // use mergeSort , plus the Time O(nlogn)
//            Arrays.stream(tempLowArr).forEach(s -> {
//                System.out.print(s + ",");
//            });
//
//        }


        private int[] clip(int[] tempLowArr, int size) {
            int[] ints = new int[size];
            System.arraycopy(tempLowArr, 0, ints, 0, size);
            return ints;
        }

    }


}
